<?php
/**
 * Created by PhpStorm.
 * User: syzhou
 * Date: 2019-03-20
 * Time: 15:47
 */

/**
 * @param $path
 * @param bool $isDir
 * @param int $mode
 * @return bool true on success or false on failure.
 */
function ensureDirExists($path, $isDir = true, $mode = 0755)
{
    $dir = $isDir ? $path : dirname($path);
    return is_dir($dir) ? true : mkdir($dir, $mode, true);
}

/**
 * 递归复制目录
 * @param $source
 * @param $dest
 * @return int 0: 成功; 负数: 失败
 */
function copyDir($source, $dest)
{
    if (file_exists($dest)) {
        return -1;
    }
    if (!mkdir($dest, 0755, true)) {
        return -2;
    }
    $iterator = new \RecursiveIteratorIterator(
        new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
        \RecursiveIteratorIterator::SELF_FIRST);
    foreach ($iterator as $item) {
        if ($item->isDir()) {
            if (!mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName(), 0755, true)) {
                return -3;
            }
        } else {
            if (!copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) {
                return -3;
            }
        }
    }
    return 0;
}

/**
 * 读取 csv 文件
 * @param string $path 文件路径
 * @return array 二维数组，null 表示失败
 */
function read_csv_file($path)
{
    $fin = fopen($path, 'r');
    if ($fin === false) {
        return null;
    }
    $items = [];
    while (is_array($item = fgetcsv($fin))) {
        if (count($item) == 1 && $item[0] === null) {
            continue;
        }
        $items[] = $item;
    }
    fclose($fin);
    return $items;
}

/**
 * @param $path
 * @param $items
 * @return bool 是否成功
 */
function write_csv_file($path, $items)
{
    if (!ensureDirExists($path, false)) {
        return false;
    };
    $fout = fopen($path, 'w');
    if ($fout === false) {
        return false;
    }
    foreach ($items as $item) {
        fputcsv($fout, $item);
    }
    return fclose($fout);
}

/**
 * @param $path
 * @param bool $object_as_array
 * @return mixed
 */
function json_decode_from_file($path, $object_as_array = false)
{
    $content = file_get_contents($path);
    return json_decode($content, $object_as_array);
}

/**
 * @param $path
 * @param $data
 * @param int $options
 * @return bool 是否成功
 */
function json_encode_to_file($path, $data, $options = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
{
    $content = json_encode($data, $options);
    if (!ensureDirExists($path, false)) {
        return false;
    }
    return false !== file_put_contents($path, $content);
}